<?php
namespace App\Http\Controllers\Front;

use App\Service\Front\UserService;
use Illuminate\Http\Request;

class WxAuthController extends BaseController
{
    //微信授权

    protected $app_id = 'wx4171136552ce7ceb';
    protected $app_secret = '3d2f7af5eb6301eda5660c54f6fd92bf';

    /**
     * 用户详细授权，access_token
     */
    public function wxtoken(Request $request)
    {
        //GET（请使用https协议） https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        $appid = $this->app_id; //env('WECHAT_APPID');
        $appsecret = $this->app_secret; //env('WECHAT_SECRET');
        $token = $request->get('token', '');
        $code = $request->get('code', '');
        $nickname = $request->get('nickname', '');
        $avatarUrl = $request->get('avatarUrl', '');
        $token = $request->get('token', ''); //登录token
        if (!$token) {
            return $this->toJson(-2, '未登录');
        }
        $uid = (new UserService())->uidByToken($token);
        if (!$uid) {
            return $this->toJson(-2, '登录过期或用户不存在');
        }
        if (!$code) {
            return $this->toJson(-2, 'CODE必须的');
        }
        if ($code == '0000') {
            $openid = $code;
        } else {
            $url = 'https://api.weixin.qq.com/sns/jscode2session';
            $url .= '?appid=' . $appid;
            $url .= '&secret=' . $appsecret;
            $url .= '&js_code=' . $code;
            $url .= '&grant_type=authorization_code';
            $resCurl = $this->wxCurl($url);
            $openid = $resCurl['data']['openid'];
        }
        $pas = [
            'openid' => $openid,
            'nickname' => $nickname,
            'avatarUrl' => $avatarUrl,
        ];
        $res = (new UserService())->wxByOpenid($uid, $pas);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        $resData = [
            'openid' => $openid,
        ];
        return $this->toJson(0, '', $resData);
    }

    /**
     * 构建CURL请求，单线程
     * @param $url 请求地址
     * @param $string 参数拼接的字符串
     * @param $method 请求方式：put、post、get、delete
     * @return $json
     */
    public function wxCurl($url)
    {
        $curl = curl_init(); //初始化
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        $output = curl_exec($curl);
        curl_close($curl);
        if (!$output) {
            return array('code'=>-1, 'msg'=>'请求失败');
        }
        $items = json_decode($output,true);
        return array('code' => 0, 'msg' => 'success', 'data' => $items);
    }
}